package com.bscc.common.interceptor;

import com.bscc.common.model.Menu;
import com.bscc.common.model.User;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

public class UserInterceptor implements Interceptor
{

    public void intercept(Invocation inv)
    {
        Controller controller = inv.getController();
        User user = controller.getSessionAttr("user");
        // 用户如果没有登录，那么就跳转到登录页面
        if (null == user)
        {
            controller.redirect("/admin/reLogin");
        }
        else
        {
            boolean hasPermission = false;

            if( null != user.getRole())
            {
                if(1 == user.getRole())
                    hasPermission = true;
                else if(null != user.getMenuList() || user.getMenuList().size() > 0)
                {
                    String currentActionKey = inv.getActionKey();
                    if(currentActionKey.endsWith("edit"))
                        currentActionKey = currentActionKey.replace("edit", "update");
                    else if(currentActionKey.endsWith("add"))
                        currentActionKey = currentActionKey.replace("add", "save");
                    else if(currentActionKey.endsWith("userSet"))
                        currentActionKey = currentActionKey.replace("userSet", "updateByUser");

                    for(Menu m: user.getMenuList())
                    {
                        if(currentActionKey.equals(m.getPermission()))
                        {
                            hasPermission = true;
                            break;
                        }
                    }
                }
            }

            if(!hasPermission)
            {
                controller.setAttr("code", "401");
                controller.setAttr("msg", "您无此权限");
                controller.renderJson();
            }
            else
                inv.invoke();

        }
    }
}
